import { defineStore } from 'pinia'
import type { Router } from 'vue-router'
import { v4 as uuidv4 } from 'uuid'

// 定义全局store类型
export interface AppState {
  isLoading: boolean
  isDarkMode: boolean
  currentSessionId: string
  apiBaseUrl: string
  router: any | null
}

// 全局应用store
export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    isLoading: false,
    isDarkMode: false,
    currentSessionId: '',
    apiBaseUrl: '/api',
    router: null
  }),

  getters: {
    // 获取当前会话ID，如果不存在则生成一个新的
    getCurrentSessionId(): string {
      if (!this.currentSessionId) {
        // 从localStorage获取已保存的会话ID，如果没有则生成新的UUID
        const savedSessionId = localStorage.getItem('currentSessionId')
        this.currentSessionId = savedSessionId || uuidv4()
        if (!savedSessionId) {
          localStorage.setItem('currentSessionId', this.currentSessionId)
        }
      }
      return this.currentSessionId
    }
  },

  actions: {
    // 设置加载状态
    setLoading(loading: boolean) {
      this.isLoading = loading
    },

    // 切换暗黑模式
    toggleDarkMode() {
      this.isDarkMode = !this.isDarkMode
      // 这里可以添加暗黑模式的具体实现
    },

    // 设置会话ID
    setSessionId(sessionId: string) {
      this.currentSessionId = sessionId
    },

    // 生成新的UUID格式会话ID
    generateSessionId(): string {
      const newSessionId = uuidv4()
      this.currentSessionId = newSessionId
      localStorage.setItem('currentSessionId', newSessionId)
      return newSessionId
    },

    // 设置路由实例
    setRouter(router: Router) {
      this.router = router
    },

    // 导航到指定路由
    navigateTo(route: string, params?: Record<string, any>) {
      if (this.router) {
        this.router.push({
          path: route,
          query: params
        })
      }
    }
  }
})

// 导出所有子store
export * from './chat'
export * from './session'
export * from './documents'
export * from './learning'
export * from './settings'
